package com.my.chapter17;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class practice27 {
    public static void main(String[] args) {
        Map<CountedString2,Integer> map =
                new HashMap<CountedString2,Integer>();
        CountedString2[] cs = new CountedString2[5];
        for(int i = 0; i < cs.length; i++) {
            cs[i] = new CountedString2("hi");
            map.put(cs[i], i); // Autobox int -> Integer
        }
        for(CountedString2 cstring : cs) {
            System.out.println("Looking up " + cstring);
            System.out.println(map.get(cstring));
        }
    }
}

class CountedString2 {
    private static List<String> created =
            new ArrayList<String>();
    private String s;
    private int id = 0;
    public CountedString2(String str) {
        s = str;
        created.add(s);
        for(String s2 : created)
            if(s2.equals(s))
                id++;
    }
    public String toString() {
        return "String: " + s + " id: " + id +
                " hashCode(): " + hashCode();
    }
    public int hashCode() {
        int result = 17;
        result = 37 * result + s.hashCode();
        // result = 37 * result + id;
        return result;
    }
    public boolean equals(Object o) {
        return o instanceof CountedString2 &&
                s.equals(((CountedString2)o).s) &&
                id == ((CountedString2)o).id;
    }
}
